package jt.classic.system.objectquery;

import jt.classic.system.ISystem;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectLCManager;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;
import jt.classic.system.workflow.WObject;
import jt.classic.system.workflow.WObjectRegister;

import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import org.limp.basework.Table;
import org.limp.basework.analyzer.TableRegisterCenter;
import org.limp.basework.impl.CommonBean4HSQ;

import org.limp.mine.Controller;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;

import java.sql.Connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 对象实体数据集合查询控制器
 *
 * @author mido
 *
 */
public class ObjectARGAction extends DispatchAction {
    /**
        * 查询项组件
        * @param mapping
        * @param form
        * @param request
        * @param response
        * @return
        * @throws Exception
        */
    public ActionForward querycmp(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        if (ISystem.invalidSesstion(request)) {
            IUser user = UserManager.createGuestUser();

            ISystem.createSessionUser(request, user);
        }

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        param.put("sessionUserLogid", user.ilogid());
        param.put("sessionUserId", user.id());
        param.put("sessionUserName", user.iname());
        param.put("sessionGroupId", user.igroup().id());
        param.put("sessionGroupName", user.igroup().iname());
        param.put("sessionGroupNumber", user.igroup().inumber());

        String querykey = StringTool.checkString(param.get("querykey"));

        ObjectQuery wquery = null;

        WObject object = null;

        if (querykey.equals("")) {
            request.setAttribute("result",
                "{success: false, msg : '没有指定查询key,无法初始化查询项'}");
        } else {
            ObjectQueryRegister qregister = ObjectQueryRegister.getInstance();
            wquery = qregister.get(querykey);
            object = wquery.iobject();
        }

        if (wquery == null) {
            request.setAttribute("result",
                "{success: false, msg : '通用查询设置无效,无法初始化查询项'}");
        } else if (object == null) {
            request.setAttribute("result",
                "{success: false, msg : '查询关联对象没有注册,无法初始化查询项'}");
        } else {
            List list = new ArrayList();

            List queryList = wquery.iqueryitems();

            if ((queryList != null) && !queryList.isEmpty()) {
                for (int i = 0; i < queryList.size(); i++) {
                    ObjectQueryItem item = (ObjectQueryItem) queryList.get(i);

                    String paramValue = item.iparam();

                    if (paramValue.startsWith("@")) {
                        paramValue = StringTool.checkString(param.get(
                                    paramValue.substring(1)));
                    }

                    ObjectQueryItemJsonBean bean = new ObjectQueryItemJsonBean();
                    bean.setName(item.ilabel());
                    bean.setColumn(item.icolumn().getName());
                    bean.setColumnName(item.icolumn().getDescription());
                    bean.setItemType(1);
                    bean.setMode(item.imode());
                    bean.setParam(paramValue);
                    bean.setTable(item.icolumn().associateTable().getName());
                    bean.setTableName(item.icolumn().associateTable()
                                          .getDescription());
                    bean.setType(item.itype());
                    bean.setColumnType(item.icolumn().getType().toString());
                    bean.setTableHandleType(StringTool.checkString(
                            object.handleTable(item.icolumn().associateTable())));

                    list.add(bean);
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(list);

            String jsonString = "{success: true, \"queryCmp\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        }

        return mapping.findForward("jsonresult");
    }

    /**
    * 查询列表显示项组件
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
    public ActionForward modelcmp(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        if (ISystem.invalidSesstion(request)) {
            IUser user = UserManager.createGuestUser();

            ISystem.createSessionUser(request, user);
        }

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        param.put("sessionUserLogid", user.ilogid());
        param.put("sessionUserId", user.id());
        param.put("sessionUserName", user.iname());
        param.put("sessionGroupId",
            (user.igroup() != null) ? user.igroup().id() : "");
        param.put("sessionGroupName",
            (user.igroup() != null) ? user.igroup().iname() : "");
        param.put("sessionGroupNumber",
            (user.igroup() != null) ? user.igroup().inumber() : "");

        String querykey = StringTool.checkString(param.get("querykey"));

        String comptype = StringTool.checkString(param.get("comptype"));

        ObjectQuery wquery = null;

        WObject object = null;

        if (querykey.equals("")) {
            request.setAttribute("result",
                "{success: false, msg : '没有指定查询key,无法初始化系统对象数据列表'}");
        } else {
            ObjectQueryRegister qregister = ObjectQueryRegister.getInstance();
            wquery = qregister.get(querykey);
            object = wquery.iobject();
        }

        if (wquery == null) {
            request.setAttribute("result",
                "{success: false, msg : '通用查询设置无效,无法初始化数据列表'}");
        } else if (object == null) {
            request.setAttribute("result",
                "{success: false, msg : '查询关联对象没有注册,无法初始化数据列表'}");
        } else {
            StringBuffer columnModleString = new StringBuffer(
                    "{'header': '<font class=\"oaFont\">序号</font>','dataIndex': 'PAGINATION_NUMBER','width':20}");

            StringBuffer fieldsNames = new StringBuffer(
                    "{name: 'PAGINATION_NUMBER'},{name: 'ID'},");

            List viewList = wquery.iviewitems();

            if ((viewList != null) && !viewList.isEmpty()) {
                for (int i = 0; i < viewList.size(); i++) {
                    ObjectQueryItem item = (ObjectQueryItem) viewList.get(i);

                    if (!item.ishow().equals("-1")) {
                        columnModleString.append(
                            ",{'header': '<font class=\"oaFont\">" +
                            item.ilabel() + "</font>','dataIndex': '" +
                            item.ifieldName() + "',sortable : true, clazz : '" +
                            item.iclass() + "', renderer: render" + comptype +
                            "Header}");
                    }

                    fieldsNames.append(",{name: '" + item.ifieldName() + "'}");
                }
            }

            List list = new ArrayList();

            List queryList = wquery.iqueryitems();

            if ((queryList != null) && !queryList.isEmpty()) {
                for (int i = 0; i < queryList.size(); i++) {
                    ObjectQueryItem item = (ObjectQueryItem) queryList.get(i);

                    String paramValue = (String) item.iparam();

                    if (paramValue.startsWith("@")) {
                        paramValue = StringTool.checkString(param.get(
                                    paramValue.substring(1)));
                    }

                    ObjectQueryItemJsonBean bean = new ObjectQueryItemJsonBean();
                    bean.setName(item.ilabel());
                    bean.setColumn(item.icolumn().getName());
                    bean.setColumnName(item.icolumn().getDescription());
                    bean.setItemType(1);
                    bean.setMode(item.imode());
                    bean.setParam(paramValue);
                    bean.setNeed(item.ineed());
                    bean.setPointId(item.ipointId());
                    bean.setPointName(item.ipointName());
                    bean.setTable(item.icolumn().associateTable().getName());
                    bean.setTableName(item.icolumn().associateTable()
                                          .getDescription());
                    bean.setType(item.itype());
                    bean.setColumnType(item.icolumn().getType().toString());
                    bean.setTableHandleType(StringTool.checkString(
                            object.handleTable(item.icolumn().associateTable())));

                    list.add(bean);
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(list);

            request.setAttribute("result",
                "{success: true, title: '" + wquery.iname() + "',showchk : '" +
                wquery.ishowchk() + "',js:'" + wquery.iJsUrl() + "',css:'" +
                wquery.iCssUrl() + "', defaultlist : '" +
                wquery.idefaultlist() + "', exportlist : '" + wquery.iexport() +
                "', columModel: [" + columnModleString.toString() +
                "], fieldsNames : [" + fieldsNames.toString() +
                "], queryCmp: " + jsonArray.toString() + "}");
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 执行对象实例查询操作
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        if (ISystem.invalidSesstion(request)) {
            IUser user = UserManager.createGuestUser();

            ISystem.createSessionUser(request, user);
        }

        IUser user = ISystem.getSessionUser(request);

        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String pageNO = StringTool.checkString(param.get("pageNO"));

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        String querykey = StringTool.checkString(param.get("querykey"));

        String orderby = StringTool.checkString(param.get("orderby"));

        String orderbykey = StringTool.checkString(param.get("orderbykey"));

        String queryAction = StringTool.checkString(param.get("queryAction"));

        param.put("sessionUserLogid", user.ilogid());
        param.put("sessionUserId", user.id());
        param.put("sessionUserName", user.iname());
        param.put("sessionGroupId",
            (user.igroup() != null) ? user.igroup().id() : "");
        param.put("sessionGroupName",
            (user.igroup() != null) ? user.igroup().iname() : "");
        param.put("sessionGroupNumber",
            (user.igroup() != null) ? user.igroup().inumber() : "");

        WObject object = null;

        ObjectQuery wquery = null;

        if (querykey.equals("")) {
            request.setAttribute("result",
                "{success: false, msg : '没有指定查询key,无法初始化系统对象数据列表'}");
        } else {
            ObjectQueryRegister qregister = ObjectQueryRegister.getInstance();
            wquery = qregister.get(querykey);
            object = wquery.iobject();
        }

        if (wquery == null) {
            request.setAttribute("result",
                "{success: false, msg : '通用查询设置无效,无法初始化数据列表'}");
        } else if (object == null) {
            request.setAttribute("result",
                "{success: false, msg : '查询关联对象没有注册,无法初始化数据列表'}");
        } else {
            /*初始化时不显示列表数据*/
            if (queryAction.equals("") && !wquery.idefaultlist()) {
                String jsonString = "{\"pageNO\":\"1\",\"totalPage\":\"0\",\"totalCount\":\"0\",\"queryList\":{}}";

                request.setAttribute("result", jsonString);
            } else {
                String orderbyTableName = orderbykey.equals("") ? ""
                                                                : orderbykey.substring(0,
                        orderbykey.indexOf("."));

                String orderbyColumnName = orderbykey.equals("") ? ""
                                                                 : orderbykey.substring(orderbykey.indexOf(
                            ".") + 1);

                Map validTable = new HashMap();

                List viewList = wquery.iviewitems();

                if ((viewList != null) && !viewList.isEmpty()) {
                    for (int i = 0; i < viewList.size(); i++) {
                        ObjectQueryItem item = (ObjectQueryItem) viewList.get(i);

                        if (!item.ialien()) {
                            if (!validTable.containsKey(
                                        item.icolumn().associateTable().getName())) {
                                validTable.put(item.icolumn().associateTable()
                                                   .getName(),
                                    item.icolumn().associateTable().getName());
                            }
                        }
                    }
                }

                String sql = ObjectARGTool.getListSQL4Query(user, object,
                        wquery, param);

                request.setAttribute("orderby", orderby);

                request.setAttribute("orderbykey", orderbykey);

                request.setAttribute("objectquery", wquery);

                request.setAttribute("object", object);

                request.setAttribute("query", param);

                String sql1 = "SELECT COUNT(*) FROM (" + sql + ") TAB";

                String sql2 = "SELECT A.ID FROM ISYS_OBJECT A,(" + sql +
                    ") B WHERE A.ID = B.ID ORDER BY A.OBJ_CREATETIME DESC";

                if (!orderbykey.equals("") &&
                        orderbyTableName.equals("ISYS_OBJECT")) {
                    sql2 = "SELECT A.ID FROM ISYS_OBJECT A,(" + sql +
                        ") B WHERE A.ID = B.ID ORDER BY A." +
                        orderbyColumnName + " " + orderby;
                } else if (!orderbykey.equals("") &&
                        !orderbyTableName.equals("ISYS_OBJECT")) {
                    TableRegisterCenter center = TableRegisterCenter.getInstance();

                    Table table = center.findTable(orderbyTableName);

                    sql2 = "SELECT A.ID FROM ISYS_OBJECT A,(" + sql +
                        ") B,ISYS_OBJECT_RELATION C," + orderbyTableName +
                        " D WHERE A.ID = B.ID AND A.ID = C.ID AND C.OBJ_TABLE = '" +
                        orderbyTableName + "' AND C.OBJ_PKID = D." +
                        table.getPrimaryKey()[0] + " ORDER BY D." +
                        orderbyColumnName + " " + orderby + "";
                }

                String url = jt.classic.system.ISystem.getContextPath() +
                    "/system/objectarg.do?querykey=" + querykey;

                try {
                    SystemDataSource ds = SystemDataSource.getInstance();
                    conn = ds.getConnection();

                    QueryJack plus = QueryJackFactory.getInstance()
                                                     .createQueryJack(false);

                    // 设置
                    plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
                    plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
                    plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
                    plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING,
                        url);
                    plus.setParameter(QueryJackFactory.PAGINATION_COUNT, size);
                    plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

                    // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
                    List resultList = plus.work();

                    if ((resultList != null) && !resultList.isEmpty()) {
                        ObjectManager manager = new ObjectManager(conn);

                        ObjectLCManager lcmanager = new ObjectLCManager(conn);

                        for (int i = 0; i < resultList.size(); i++) {
                            Map info = (Map) resultList.get(i);
                            String id = (String) info.get("ID");
                            String number = (String) info.get(
                                    "PAGINATION_NUMBER");

                            IObject obj = manager.getObjectShellById(id);

                            info.put("OBJ_CREATETIME", obj.icreatetime());
                            info.put("OBJ_UPDATETIME", obj.iupdatetime());
                            info.put("OBJ_KEY", obj.ikey());
                            info.put("OBJ_KEYWORD", obj.ikeyword());
                            info.put("OBJ_REMARK", obj.idesc());
                            info.put("OBJ_CREATORID", obj.icreator().id());
                            info.put("OBJ_CREATORNAME", obj.icreator().iname());
                            info.put("USER_LOGID", obj.icreator().ilogid());
                            info.put("OBJ_UNITID", obj.icreator().igroup().id());
                            info.put("OBJ_UNITNAME",
                                obj.icreator().igroup().iname());
                            info.put("UNIT_FLUMELABEL",
                                obj.icreator().igroup().iflumelabel(","));
                            info.put("UNIT_FLUMEID",
                                obj.icreator().igroup().iflumeid(","));

                            if (validTable != null) {
                                Iterator iter = validTable.keySet().iterator();

                                while (iter.hasNext()) {
                                    String tableName = (String) iter.next();

                                    Table table = object.itable(tableName);

                                    List tableInfoList = lcmanager.getObjectContentById(id,
                                            object, tableName);

                                    List viewItemList = wquery.iviewitems(tableName);

                                    /*单一数据*/
                                    if ((tableInfoList != null) &&
                                            (tableInfoList.size() == 1)) {
                                        Map tableInfo = (Map) tableInfoList.get(0);

                                        if ((viewItemList != null) &&
                                                !viewItemList.isEmpty()) {
                                            for (int j = 0;
                                                    j < viewItemList.size();
                                                    j++) {
                                                ObjectQueryItem item = (ObjectQueryItem) viewItemList.get(j);

                                                Object o = tableInfo.get(item.icolumn()
                                                                             .getName());

                                                info.put(item.icolumn().getName(),
                                                    o);
                                            }
                                        }
                                    }
                                    /*多条数据*/
                                    else if ((tableInfoList != null) &&
                                            (tableInfoList.size() > 1)) {
                                        if ((viewItemList != null) &&
                                                !viewItemList.isEmpty()) {
                                            for (int j = 0;
                                                    j < viewItemList.size();
                                                    j++) {
                                                ObjectQueryItem item = (ObjectQueryItem) viewItemList.get(j);

                                                List itemValueList = new ArrayList();

                                                for (int k = 0;
                                                        k < tableInfoList.size();
                                                        k++) {
                                                    Map itemInfo = (Map) tableInfoList.get(k);

                                                    Object o = itemInfo.get(item.icolumn()
                                                                                .getName());

                                                    if (o == null) {
                                                        System.out.println(item.icolumn()
                                                                               .associateTable()
                                                                               .getName() +
                                                            "<---->" +
                                                            item.icolumn()
                                                                .getName());
                                                    }

                                                    itemValueList.add(o);
                                                }

                                                info.put(item.icolumn().getName(),
                                                    itemValueList);
                                            }
                                        }
                                    }

                                    obj.iSetContent(table, tableInfoList);
                                }
                            }
                        }
                    }

                    // 显示标签
                    Label label = plus.getLabel();

                    JSONArray jsonArray = JSONArray.fromObject(resultList);

                    String jsonString = "{\"pageNO\":\"" + label.current() +
                        "\",\"totalPage\":\"" + label.totalfan() +
                        "\",\"totalCount\":\"" + label.totaldata() +
                        "\",\"queryList\":";
                    jsonString += jsonArray.toString();
                    jsonString += "}";

                    request.setAttribute("result", jsonString);
                } catch (Exception ex) {
                    request.setAttribute("result", "{success: false}");
                    ISystem.catchException(request, this, ex);
                } finally {
                    SystemDataSource.closeConnection(conn);
                }
            }
        }

        return mapping.findForward("jsonresult");
    }
}
